import { defineStore } from "pinia";
import { ref } from "vue";
import ManageToken from "@/utils/token";
import Login from "@/api/login";

const useLoginStore = defineStore('login', () => {
    const token = ref(ManageToken.getToken() || '')
    const userInfo = ref({})
    const setToken = newToken => {
        token.value = newToken
        ManageToken.setToken(newToken)
    }
    const loginAction = async loginForm => {
        const resp = await Login.loginApi(loginForm)
        const { token: newToken } = resp
        setToken(newToken)
    }
    const setUserInfo = (user) => {
        userInfo.value = user
    }
    const getUserInfoAction = async () => {
        try {
            const resp = await Login.getUserInfoApi()
            setUserInfo(resp)
        } catch (e) { }
    }
    const logoutAction = () => {
        ManageToken.removeToken()
        token.value = ''
        userInfo.value = {}
    }
    return {
        token,
        userInfo,
        loginAction,
        logoutAction,
        getUserInfoAction
    }
})

export default useLoginStore